/*
 * @lc app=leetcode.cn id=525 lang=typescript
 *
 * [525] 连续数组
 */

// @lc code=start
function findMaxLength(nums: number[]): number {
  let size = nums.length;
  if (size < 2) return 0;

  let result = 0;
  let prefix = 0;
  const hash: Map<number, number> = new Map([[0, -1]]);

  for (let i = 0; i < size; i++) {
    const num = nums[i];
    if (num === 1) {
      prefix++;
    } else if (num === 0) {
      prefix--;
    }
    if (hash.has(prefix)) {
      result = Math.max(result, i - hash.get(prefix));
    } else {
      hash.set(prefix, i);
    }
  }
  return result;
}
// @lc code=end
